<template>
  <div class="chat-app">
    <!-- 导航栏 -->
    <div class="navbar">
      <div class="navbar-left">
        <span class="app-name">Chat App</span>
      </div>
      <div class="navbar-right">
        <input type="text" class="search-box" placeholder="Search..." />
        <div class="user-avatar" @click="showUserMenu">
          <img src="/static/images/test-avt.jpg" alt="Avatar" />
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧好友列表 -->
      <div class="friend-list">
        <div
          v-for="friend in friends"
          :key="friend.id"
          class="friend-item"
          :class="{ active: selectedFriend?.id === friend.id }"
          @click="selectFriend(friend)"
        >
          <!-- 好友头像 -->
          <div class="friend-avatar" @click.stop="showFriendDetails(friend)">
            {{ friend.name[0] }}
          </div>
          <div class="friend-info">
            <div class="friend-name">{{ friend.name }}</div>
            <div class="friend-last-message">{{ friend.lastMessage }}</div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天窗口 -->
      <div class="chat-window">
        <div class="messages">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.sender]"
          >
            <!-- 消息头像 -->
            <div class="message-avatar">
              <img
                v-if="message.sender === 'friend'"
                :src="selectedFriend.avatar"
                alt="Friend Avatar"
                @click="showFriendDetails(selectedFriend)"
              />
              <img
                v-else
                src="/static/images/test-avt.jpg"
                alt="My Avatar"
              />
            </div>
            <div class="message-content">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </div>
        </div>
        <div class="input-area">
          <input
            v-model="newMessage"
            @keyup.enter="sendMessage"
            placeholder="Type a message..."
          />
          <button @click="sendMessage">Send</button>
        </div>
      </div>
    </div>

    <!-- 好友详情弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <h2>{{ selectedFriend.name }}</h2>
        <p><strong>Last Message:</strong> {{ selectedFriend.lastMessage }}</p>
        <p><strong>Status:</strong> {{ selectedFriend.status || 'Online' }}</p>
        <button @click="closeModal">Close</button>
      </div>
    </div>

    <!-- 用户菜单弹窗 -->
    <div v-if="showUserMenuModal" class="modal-overlay" @click="closeUserMenu">
      <div class="modal-content user-menu" @click.stop>
        <ul>
          <!-- 暂时不放开 -->
          <!-- <li @click="handleUserMenuClick('Profile')">Profile</li>
          <li @click="handleUserMenuClick('Settings')">Settings</li> -->
          <li @click="handleUserMenuClick('logout')">Logout</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { useCacheStore } from '@/store/cache/cache';
import { computed } from 'vue';

export default {
  
  data() {
    
    
    return {
       // WebSocket 实例
       ws: null,
      // 连接状态
      connectionStatus: '',
      // 输入框内容
      newMessage: '',
      // 好友列表数据
      friends: [
        {
          id: 1,
          name: 'Alice',
          lastMessage: 'Hi there!',
          status: 'Online',
          avatar: '/static/images/test-avt.jpg',
          messages: [
            { sender: 'friend', content: 'Hi there!', time: '10:00 AM' },
            { sender: 'me', content: 'Hello!', time: '10:01 AM' },
          ],
        },
        {
          id: 2,
          name: 'Bob',
          lastMessage: 'How are you?',
          status: 'Away',
          avatar: '/static/images/test-avt.jpg',
          messages: [
            { sender: 'friend', content: 'How are you?', time: '11:00 AM' },
            { sender: 'me', content: 'I am fine, thanks!', time: '11:01 AM' },
          ],
        },
        {
          id: 3,
          name: 'Charlie',
          lastMessage: 'See you later!',
          status: 'Offline',
          avatar: '/static/images/test-avt.jpg',
          messages: [
            { sender: 'friend', content: 'See you later!', time: '12:00 PM' },
            { sender: 'me', content: 'Bye!', time: '12:01 PM' },
          ],
        },
      ],
      // 当前选中的好友
      selectedFriend: null,
      // 当前显示的聊天消息
      messages: [],
      // 是否显示好友详情弹窗
      showModal: false,
      // 是否显示用户菜单弹窗
      showUserMenuModal: false,
      // 输入框内容
      newMessage: '',
    };
  },
  methods: {
    
    // 初始化 WebSocket 连接
    initWebSocket(){ 
      const cacheStore = useCacheStore();
       // 获取缓存数据
      // const cache = JSON.stringify(cachedData)
      console.log("当前的缓存数据为：{}",JSON.stringify(cacheStore.cachedData) )
      const BASE_URL = 'localhost:8808';
      const wsScheme = window.location.protocol === 'https:' ? 'wss://' : 'ws://'
      const wsUrl = wsScheme+ BASE_URL + '/ws/chat/123456789/3'
      

      this.ws = new WebSocket(wsUrl)
      
      this.ws.onopen = () => {
        this.connectionStatus = 'Connected'
        console.log('WebSocket connected')
      }

      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data)
        this.handleReceivedMessage(message)
      }

      this.ws.onerror = (error) => {
        this.connectionStatus = 'Connection error'
        console.error('WebSocket error:', error)
      }

      this.ws.onclose = () => {
        this.connectionStatus = 'Disconnected'
        console.log('WebSocket closed')
      }
    },

    // 处理接收到的消息
    handleReceivedMessage(message) {
      const friend = this.friends.find(f => f.id === message.senderId)
      if (friend) {
        friend.messages.push({
          sender: 'friend',
          content: message.content,
          time: new Date().toLocaleTimeString([], { 
            hour: '2-digit', 
            minute: '2-digit' 
          })
        })
        friend.lastMessage = message.content
      }
    },
    // 选择好友
    selectFriend(friend) {
      this.selectedFriend = friend;
      this.messages = friend.messages; // 加载好友的聊天记录
    },
    // 显示好友详情弹窗
    showFriendDetails(friend) {
      this.selectedFriend = friend;
      this.showModal = true;
    },
    // 关闭好友详情弹窗
    closeModal() {
      this.showModal = false;
    },
    // 显示用户菜单弹窗
    showUserMenu() {
      this.showUserMenuModal = true;
    },
    // 关闭用户菜单弹窗
    closeUserMenu() {
      this.showUserMenuModal = false;
    },
    // 处理用户菜单点击事件
    handleUserMenuClick(action) {
      if (this[action] && typeof this[action] === 'function') {
        this[action]();
      }
      this.closeUserMenu();
    },
    // 发送消息
    sendMessage() {
      if (!this.newMessage.trim() || !this.selectedFriend) return

      // 构建消息对象
      const message = {
        receiverId: this.selectedFriend.id,
        content: this.newMessage,
        timestamp: new Date().getTime()
      }

      // 通过 WebSocket 发送
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify(message))
      } else {
        console.error('WebSocket is not connected')
        return
      }

      // 更新本地消息列表
      this.selectedFriend.messages.push({
        sender: 'me',
        content: this.newMessage,
        time: new Date().toLocaleTimeString([], { 
          hour: '2-digit', 
          minute: '2-digit' 
        })
      })

      this.newMessage = ''
    },
  },
  mounted() {
    this.initWebSocket()
    if (this.friends.length > 0) {
      this.selectedFriend = this.friends[0]
    }
  },
  beforeUnmount() {
    if (this.ws) {
      this.ws.close()
    }
  }
};
</script>

<style scoped>
/* 重置默认样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 全屏布局 */
.chat-app {
  display: flex;
  flex-direction: column;
  width: 100vw;
  height: 100vh;
  background-color: #fff;
}

/* 导航栏 */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  height: 60px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.navbar-left .app-name {
  font-size: 20px;
  font-weight: bold;
}

.navbar-right {
  display: flex;
  align-items: center;
}

.search-box {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  margin-right: 10px;
}

.user-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
}

/* 主内容区域 */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧好友列表 */
.friend-list {
  width: 250px;
  height: calc(100vh - 60px); /* 减去导航栏高度 */
  overflow-y: auto;
  border-right: 1px solid #ccc;
  background-color: #f9f9f9;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.friend-item:hover {
  background-color: #e9ecef;
}

.friend-item.active {
  background-color: #f0f0f0; /* 灰白色 */
}

.friend-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #007bff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  margin-right: 10px;
  cursor: pointer;
}

.friend-info {
  flex: 1;
}

.friend-name {
  font-weight: bold;
}

.friend-last-message {
  font-size: 0.9em;
  color: #666;
}

/* 右侧聊天窗口 */
.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px); /* 减去导航栏高度 */
  background-color: #fff;
}

.messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.message.me {
  justify-content: flex-end;
}

.message.friend {
  justify-content: flex-start;
}

.message-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message-text {
  padding: 8px 12px;
  border-radius: 12px;
  background-color: #e9ecef;
}

.message.me .message-text {
  background-color: #007bff;
  color: white;
}

.message-time {
  font-size: 0.8em;
  color: #666;
  margin-top: 4px;
}

/* 输入框区域 */
.input-area {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #ccc;
  height: 60px; /* 固定输入框区域高度 */
}

.input-area input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 8px;
  height: 40px; /* 固定输入框高度 */
}

.input-area button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  height: 40px; /* 固定按钮高度 */
}

.input-area button:hover {
  background-color: #0056b3;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  width: 300px;
  text-align: center;
}

.modal-content h2 {
  margin-top: 0;
}

.modal-content button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}

.modal-content button:hover {
  background-color: #0056b3;
}

.user-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.user-menu li {
  padding: 10px;
  cursor: pointer;
}

.user-menu li:hover {
  background-color: #f1f1f1;
}
</style>